<?php
namespace App\Http\Controllers\backend\rbac;
use App\models\rbac\ResourceUri;
use DB ;
Use App\models\rbac\Resource;
use Request;
use App\Http\Controllers\backend\Base;

class ResourceController extends Base
{
    public function actionIndex(){
        if(!$this->isJson){
            return $this->view('rbac.resource.index');
        }
        return response()->json($this->page( Resource::query() ));
    }

    public function actionAll(){
        return Resource::all();
    }

    public function actionUri(){
        $resource_id = Request::get('resource_id',0) ;
        return ResourceUri::where('resource_id',$resource_id)->get();
    }

    public function actionSave(){
        $id = Request::get('id',0);
        if(!$this->isPost){

            $data = '""' ;
            if($id){
                $data = Resource::find($id)->toJson();
            }

            return $this->view('rbac.resource.save',['data' => $data]);
        }

        $data = Request::all() ;

        if($id){
            $model = Resource::find($id)->fill($data) ;
        }else{
            $model = new Resource($data);
        }


        if($model->validate($data) && $model->save()){
            ResourceUri::saveUris($data['uris'] , $model->id) ;
            return true ;
        }
        return $model ;
    }


    public function actionDelete(){
        $id = Request::get('id',0);
        $isDelete = Resource::find($id)->delete();
        return response()->json(['code' => 0]);
    }
}